<template>
  <div class="pay-wrap">
    <!--动态代理-支付弹窗-->
    <el-dialog title="Please Select payment method" v-model="payVisible" append-to-body width="840px" class="pay-box" :before-close="onCancelPay">
      <p style="margin: 0 0 20px 0; font-size: 14px; color: red"
        >Please confirm your package information, choose the appropriate payment method, and do not close this pop-up window until payment
        is complete.</p
      >
      <el-card class="box-card">
        <el-row>
          <el-col :span="6" class="meal-info">
            Package type
            <p class="info-msg">{{ payFormObj.title }}</p>
          </el-col>
          <el-col :span="6" class="meal-info">
            Payment amount
            <p class="info-msg">${{ payFormObj.amount }}</p>
          </el-col>
          <el-col :span="6" class="meal-info">
            Traffic Plan
            <p class="info-msg">{{ payFormObj.quantity }}G</p>
          </el-col>
          <el-col :span="6" class="meal-info">
            Duration
            <p class="info-msg">∞</p>
          </el-col>
        </el-row>
        <el-row style="margin-top: 40px">
          <el-col :span="8" class="meal-support"><img src="@/assets/ipx-proxy_21.png" alt="" />Use all proxy</el-col>
          <el-col :span="8" class="meal-support"><img src="@/assets/ipx-proxy_21.png" alt="" />Support Datacenter</el-col>
          <el-col :span="8" class="meal-support"><img src="@/assets/ipx-proxy_21.png" alt="" />24*7 Service</el-col>
        </el-row>
      </el-card>

      <el-card style="margin-top: 20px">
        <el-radio-group v-model="payFormObj.pay_way" class="pay-way-list">
          <el-radio class="item" label="usdt">
            USDT
            <img src="@/assets/ipx-proxy_156.png" class="img" />
          </el-radio>
          <el-radio class="item" label="alipay">
            AliPay
            <img src="@/assets/ipx-proxy_160.png" class="img" />
          </el-radio>
          <el-radio class="item" label="card">
            Credit Card
            <img src="@/assets/ipx-proxy_150.png" class="img" />
          </el-radio>
        </el-radio-group>
      </el-card>
      <div class="sub-tips">
        <span>All of the proxies should be used in the network outside of mainland China</span>
        <span>*Other Payment Method Contact</span>
      </div>
      <template #footer>
        <div class="pay-footer">
          <el-button type="primary" @click="goPay">Pay Now</el-button>
          <el-button type="default" @click="onCancelPay">Cancel</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 静态代理-确认订单弹框 -->
    <el-dialog title="Please confirm the order information" v-model="staticPayVisible" append-to-body width="800" class="pay-box" :before-close="onCancelPay">
      <p style="margin: 0 0 20px 0; font-size: 14px; color: red"
        >Please confirm your order, choose the appropriate payment method, and do not close this pop-up window until payment is complete.</p
      >
      <el-card class="box-card">
        <el-row>
          <el-col :span="6" class="meal-info">
            Package type
            <p class="info-msg">Static Residential-{{ payFormObj.country_code_str }}-{{ payFormObj.line_type_str }}-{{ payFormObj.business_str }}</p>
          </el-col>
          <el-col :span="6" class="meal-info">
            Usage period
            <p class="info-msg">{{ payFormObj.days }}days</p>
          </el-col>
          <el-col :span="6" class="meal-info">
            Purchase quantity
            <p class="info-msg">{{ payFormObj.quantity }}</p>
          </el-col>
          <el-col :span="6" class="meal-info">
            Payment amount
            <p class="info-msg">${{ payFormObj.amount }}</p>
          </el-col>
        </el-row>
      </el-card>

      <el-card style="margin-top: 20px">
        <el-radio-group v-model="payFormObj.pay_way" class="pay-way-list">
          <el-radio class="item" label="usdt">
            USDT
            <img src="@/assets/ipx-proxy_156.png" class="img" />
          </el-radio>
          <el-radio class="item" label="alipay">
            AliPay
            <img src="@/assets/ipx-proxy_160.png" class="img" />
          </el-radio>
          <el-radio class="item" label="card">
            Credit Card
            <img src="@/assets/ipx-proxy_150.png" class="img" />
          </el-radio>
        </el-radio-group>
      </el-card>
      <div class="sub-tips">
        <span>All of the proxies should be used in the network outside of mainland China</span>
        <span>*Other Payment Method Contact</span>
      </div>
      <template #footer>
        <div class="pay-footer">
          <el-button type="primary" size="large" :loading="loading" @click="goPay">Paid</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      title="Order details"
      v-model="orderVisible"
      append-to-body
      width="840px"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      class="pay-box"
      :before-close="onCloseOrder"
    >
      <el-card class="box-card">
        <el-row style="display: flex">
          <el-col :span="8" class="meal-support"><img src="@/assets/ipx-proxy_03.png" alt="" style="width: auto" /></el-col>
          <el-col :span="8" class="meal-support">
            <div class="order-info">
              <p>{{ orderFormObj.goods_info }}</p>
              <p class="p2">Order ID: {{ orderFormObj.order_nu }}</p>
            </div>
          </el-col>
          <el-col :span="8" class="meal-support count">${{ orderFormObj.amount }}</el-col>
        </el-row>
      </el-card>
      <el-card style="margin-top: 20px">
        <div class="countdown">
          <div class="tips">
            Payment Methods
            <p
              >Please complete the order payment within the specified time, if the payment is overtime, it will be considered as a "payment
              failure" operation. If in doubt, please contact customer service.</p
            >
          </div>
          <div class="pay-time">
            <el-countdown ref="countdownRef" @finish="onExpired" format="mm:ss" :value="expiredTime" time-indices />
          </div>
        </div>
        <div v-if="orderFormObj.pay_way == 'usdt'">
          <el-divider />
          <div>
            <p>{{ orderFormObj.pay_tip }}</p>
            <div class="qrcode">
              <img :src="orderFormObj.qrcode" alt="qrcode" />
            </div>
            <div class="receive-addr">
              <p>
                <span>Pay Address: </span>
                <span class="res-addr">{{ orderFormObj.usdt_address }}</span>
              </p>
              <!-- <el-button type="default" class="js-copy-btn" @click="onCopy()">Copy Pay Address</el-button> -->
            </div>
          </div>
          <el-divider />
          <div>Total amount: ${{ orderFormObj.amount }}</div>
          <el-divider />
          <div>
            <p>{{ orderFormObj.payment_note }}</p>
          </div>
        </div>
      </el-card>
      <template #footer>
        <div class="pay-footer">
          <el-button type="primary" size="large" :loading="checkLoading" @click="onCheckOrder">Paid</el-button>
          <el-button type="default" size="large" @click="onCloseOrder">Close</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { useI18n } from 'vue-i18n';
  import { buyDynamicApi, buyStaticApi, orderCheckApi } from '@/api/index';
  import { init } from '@airwallex/components-sdk';

  const { locale } = useI18n();

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const props = defineProps<{
    data: Array;
  }>();

  const emits = defineEmits<{
    (event: 'confirm'): void;
  }>();

  const loading = ref(false);
  const checkLoading = ref(false);
  const countdownRef = ref();
  const payVisible = ref(false);
  const staticPayVisible = ref(false);
  const orderVisible = ref(false);
  const expiredTime = ref(null);
  const payType = ref('');
  const payFormObj = reactive({});
  const orderFormObj = reactive({});

  // 取消支付
  const onCancelPay = () => {
    payVisible.value = false;
    staticPayVisible.value = false;
  };

  const onBuy = (item) => {
    payType.value = item.payType;
    if (payType.value == 'dynamic') {
      payVisible.value = true;
    } else if (payType.value == 'static') {
      staticPayVisible.value = true;
    }
    Object.assign(payFormObj, item);
  };

  const onComfirm = (item) => {
    orderVisible.value = true;
    expiredTime.value = Date.now() + 1000 * 60 * 30;
    Object.assign(orderFormObj, item);
    setTimeout(() => {
      if (orderFormObj.pay_way == 'alipay') {
        if (item.redirect_url) {
          window.open(item.redirect_url, '_blank');
        }
      } else if (orderFormObj.pay_way == 'card') {
        airwallexPay(orderFormObj.transaction_id, orderFormObj.client_secret, locale.value);
      }
    }, 400);
  };

  const goPay = () => {
    if (loading.value) return false;
    loading.value = true;
    let params = {};
    let Fn = null;
    if (payType.value == 'dynamic') {
      params = {
        goods_id: payFormObj.goods_id,
        pay_way: payFormObj.pay_way,
      };
      Fn = buyDynamicApi;
    } else if (payType.value == 'static') {
      params = {
        country_code: payFormObj.country_code,
        line_type: payFormObj.line_type,
        business: payFormObj.business,
        days: payFormObj.days,
        quantity: payFormObj.quantity,
        pay_way: payFormObj.pay_way,
      };
      Fn = buyStaticApi;
    }
    Fn(params)
      .then((res) => {
        loading.value = false;
        if (res.errcode == 0) {
          ElMessage.success(res.message || res.errmsg);
          orderVisible.value = true;
          payVisible.value = false;
          staticPayVisible.value = false;
          expiredTime.value = Date.now() + 1000 * 60 * 30;
          Object.assign(orderFormObj, res.data);
          setTimeout(() => {
            if (orderFormObj.pay_way == 'alipay') {
              if (res.data.redirect_url) {
                window.open(res.data.redirect_url, '_blank');
              }
            } else if (orderFormObj.pay_way == 'card') {
              airwallexPay(orderFormObj.transaction_id, orderFormObj.client_secret, locale.value);
            }
          }, 400);
        } else {
          ElMessage.error(res.message || res.errmsg);
        }
      })
      .catch((err) => {
        console.log('err', err);
        loading.value = false;
        ElMessage.error(err.message);
      });
  };

  const airwallexPay = async (intent_id, client_secret, locale) => {
    const { payments } = await init({
      env: 'prod',
      enabledElements: ['payments'],
    });

    payments.redirectToCheckout({
      env: 'prod',
      mode: 'payment',
      methods: ['card'], // 只显示信用卡支付方式
      allowedCardNetworks: ['visa', 'mastercard'], // 仅允许Visa和Mastercard信用卡
      currency: 'USD',
      intent_id: intent_id,
      client_secret: client_secret,
      locale: locale,
      successUrl: `${window.location.origin}/manage/center/rechargeDetails?name=${payType.value == 'dynamic' ? 1 : 2}`,
    });
  };

  const onCheckOrder = () => {
    if (checkLoading.value) return false;
    checkLoading.value = true;
    orderCheckApi({ order_nu: orderFormObj.order_nu })
      .then((res) => {
        checkLoading.value = false;
        if (res.errcode == 0) {
          ElMessage.success(res.message || res.errmsg);
          onCloseOrder();
        } else {
          ElMessage.error(res.message || res.errmsg);
        }
      })
      .catch((err) => {
        console.log('err', err);
        checkLoading.value = false;
        ElMessage.error(err.message);
      });
  };

  const onCloseOrder = () => {
    orderVisible.value = false;
    payVisible.value = false;
    staticPayVisible.value = false;
    expiredTime.value = Date.now();
    emits('confirm');
  };

  // 订单失效
  const onExpired = () => {
    console.log('The payment is overdue and the order is invalid!');
  };

  // 复制收款地址
  // const onCopy = () => {};

  defineExpose({
    onBuy,
    onComfirm,
  });

  onMounted(() => {});
</script>

<style scoped lang="scss"></style>
